package com.example.studentmanagement2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
import java.util.List;

@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 启用自定义跨域配置
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))

                // 禁用CSRF
                .csrf(csrf -> csrf.disable())

                // 配置请求权限
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/**").permitAll()  // 允许所有请求
                        .anyRequest().authenticated()        // 其他请求需认证（可选）
                );

        return http.build();
    }

    // 显式定义跨域配置
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();

        // 允许的前端地址（示例：http://localhost:3000）
        config.setAllowedOrigins(List.of("http://localhost:3000"));

        // 允许的 HTTP 方法
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));

        // 允许的请求头
        config.setAllowedHeaders(List.of("*"));

        // 允许携带凭证（如 cookies）
        config.setAllowCredentials(true);

        // 注册跨域配置到所有路径
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/api/**", config); // 覆盖所有API路径
        return source;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}